﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using RTUDataAcquisition.AppCode;
using RTUDataAcquisition.Utils.Emails;

namespace RTUDataAcquisition
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(AppDomain.CurrentDomain.BaseDirectory + @"\Log.config"));
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            SetExceptionHandler();
            Application.Run(new MainForm());
        }

        static void SetExceptionHandler()
        {
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            Application.ThreadException += Application_ThreadException;
            //AppDomain.CurrentDomain.UnhandledException +=CurrentDomain_UnhandledException;
            //TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
        }

        static void SendEmail(string title, string str)
        {
            EmialFactory.SendEmail(new Utils.Emails.Dto.SendEmailInputDto
            {
                body = str,
                SendEmialType = Utils.Emails.Enums.SendEmialType.QQ,
                SendEmails = new List<string>() { "609365252@qq.com" },
                title = title
            });
        }
        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            string title = "德希_RTU生产者_Application_ThreadException错误";
            string str = GetExceptionMsg(e.Exception, e.ToString());
            try
            {
                SendEmail(title, str);
            }
            catch (Exception ex)
            {
                Messages.SaveLog(ex, ELogLayer.UI, ELogType.Error);
            }
            Messages.SaveLog($"{title}{str}", ELogLayer.UI, ELogType.Error);
            //LogManager.WriteLog(str);
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string title = "德希_RTU生产者_CurrentDomain_UnhandledException错误";
            string str = GetExceptionMsg(e.ExceptionObject as Exception, e.ToString());
            try
            {
                SendEmail(title, str);
            }
            catch (Exception ex)
            {
                Messages.SaveLog(ex, ELogLayer.UI, ELogType.Error);
            }
            Messages.SaveLog($"{title}{str}", ELogLayer.UI, ELogType.Error);
            // 在崩溃事件处理程序中重新启动应用程序
            Process.Start(Application.ExecutablePath);
            Environment.Exit(0);
            //LogManager.WriteLog(str);
        }

        static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            string title = "德希_RTU生产者_CurrentDomain_UnhandledException错误";
            string str = GetExceptionMsg(e.Exception, e.ToString());
            try
            {
                SendEmail(title, str);
            }
            catch (Exception ex)
            {
                Messages.SaveLog(ex, ELogLayer.UI, ELogType.Error);
            }
            Messages.SaveLog($"{title}{str}", ELogLayer.UI, ELogType.Error);
            // 在崩溃事件处理程序中重新启动应用程序
            Process.Start(Application.ExecutablePath);
            Environment.Exit(0);
            //LogManager.WriteLog(str);
        }

        /// <summary>
        /// 生成自定义异常消息
        /// </summary>
        /// <param name="ex">异常对象</param>
        /// <param name="backStr">备用异常消息：当ex为null时有效</param>
        /// <returns>异常字符串文本</returns>
        static string GetExceptionMsg(Exception ex, string backStr)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("****************************未捕获的异常****************************");
            sb.AppendLine("【出现时间】：" + DateTime.Now.ToString());
            if (ex != null)
            {
                sb.AppendLine("【异常类型】：" + ex.GetType().Name);
                sb.AppendLine("【异常信息】：" + ex.Message);
                sb.AppendLine("【堆栈调用】：" + ex.StackTrace);
            }
            else
            {
                sb.AppendLine("【未处理异常】：" + backStr);
            }
            sb.AppendLine("***************************************************************");
            return sb.ToString();
        }

    }
}
